package com.tianhua.javs.core.engine.pipeline;

import com.tianhua.javs.client.bean.JavsScriptMethodBean;
import com.tianhua.javs.client.bean.JavsTranslateContextBean;
import com.tianhua.javs.client.bean.TranslateResultBean;
import com.tianhua.javs.core.constant.TagConstants;
import com.tianhua.javs.core.engine.PipelineTranslator;
import com.tianhua.javs.client.func.IScriptFunc;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Description:javs 内置的关键字或者关键字函数处理管道
 * date: 2022/2/11
 *
 * @author shenshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Component(value = "javsPipelineTranslator")
public class JavsPipelineTranslator implements PipelineTranslator {
    //func动态编排
    @Resource(name = "conditionFunc")
    private IScriptFunc conditionFunc;

    @Resource(name = "returnFunc")
    private IScriptFunc returnFunc;


    @Resource(name = "logFunc")
    private IScriptFunc logFunc;

    @Resource(name = "businessPipelineTranslator")
    private PipelineTranslator businessPipelineTranslator;


    @Override
    public String translateKeyWard(JavsTranslateContextBean translateContextBean, String javsShell, String keyWard) {
        String currentSegment = keyWard;

        //日志segment 语句 翻译
        TranslateResultBean translateResultBean = logFunc.translate(keyWard,translateContextBean.getCurrentScriptMethodBean().getScriptVarMap());
        if(translateResultBean != null){
            currentSegment = translateResultBean.getSegment();
        }

        //条件segment 语句 翻译
        translateResultBean = conditionFunc.translate(currentSegment,translateContextBean.getCurrentScriptMethodBean().getScriptVarMap());
        if(translateResultBean != null){
            currentSegment = translateResultBean.getSegment();
        }

        //返回segment 语句翻译
        translateResultBean = returnFunc.translate(currentSegment,translateContextBean.getCurrentScriptMethodBean().getScriptVarMap());
        if(translateResultBean != null){
            currentSegment = translateResultBean.getSegment();
        }

        //最后业务 segment 语句翻译
        currentSegment = businessPipelineTranslator.translateKeyWard(translateContextBean, javsShell, currentSegment);
        if(currentSegment.trim().endsWith(TagConstants.ROW_END)){
            return currentSegment;
        }
        if(currentSegment.endsWith(TagConstants.BRACE_RIGHT + "\n")){
            return currentSegment;
        }
        if(currentSegment.endsWith(TagConstants.BRACE_LEFT + TagConstants.N_LINE) || currentSegment.endsWith(TagConstants.BRACE_LEFT)){
            return currentSegment;
        }
        return currentSegment + TagConstants.ROW_END;
        //多项式展开？
        //return translateResultBean.getSegment();
    }
}
